/*
 * Copyright (c) 2020 - ~, HIT_HERO Team
 *
 * FILE MODULE SOURCE FILE
 * Used file system
 * Used in RT-Thread Operate System
 *
 * Change Logs:
 * Date           Author       Notes			QQ
 * 2020-06-04     WangXi   	   first version	1098547591
 */

#include "Module_FILE.h"
#include "drv_spi.h"
#include "spi_flash_sfud.h"
#include "dfs_fs.h"

static rt_err_t Module_FILEInit(MODULE_FILE *Dev_FILE);


rt_err_t Module_File_Config(MODULE_FILE *Dev_FILE){
	rt_err_t res = RT_EOK;
	
	if( Dev_FILE->Init==NULL
	){	
		/* Link the Method */
		Dev_FILE->Init = Module_FILEInit;	
	}
	else{
		rt_kprintf("Warning: Module FILE is Configed twice\r\n");
		return RT_ERROR;
	}

	/* Device Init */
	res = Dev_FILE->Init(Dev_FILE);
	if(res != RT_EOK){
		rt_kprintf("Error: FILE init failed\r\n");
		return RT_ERROR;
	}
	return RT_EOK;
}

static rt_err_t Module_FILEInit(MODULE_FILE *Dev_FILE){
    rt_err_t res = RT_EOK;
	
	/* Init the spi communication */
	res = rt_hw_spi_device_attach(	Dev_FILE->SpiBusName, 	Dev_FILE->SpiDevName, 
									Dev_FILE->CsPort, 		Dev_FILE->CsPinNum);
	
	if(res != RT_EOK){
		rt_kprintf("Error: Spi device attach failed\r\n");
		return RT_ERROR;
	}
	
	Dev_FILE->SPI_DevHandle = (struct rt_spi_device *)rt_device_find(Dev_FILE->SpiDevName);
	if(Dev_FILE->SPI_DevHandle == NULL){
		rt_kprintf("Error: Can't find %s device\r\n",Dev_FILE->SpiDevName);
		return RT_ERROR;
	}
	
	struct rt_spi_configuration cfg;
    cfg.data_width = 8;
    cfg.mode = RT_SPI_MASTER | RT_SPI_MODE_0 | RT_SPI_MSB;
    cfg.max_hz = 20 * 1000 *1000;                           /* 20M */
    rt_spi_configure(Dev_FILE->SPI_DevHandle, &cfg);
	
	/* Check the chip ID */
	rt_uint8_t ChipIDReg = Dev_FILE->ChipIDRegist;
	rt_uint8_t ChipID[3] = {0};
	rt_spi_send_then_recv(Dev_FILE->SPI_DevHandle, &ChipIDReg, 1, ChipID, 3);
	rt_uint32_t ChipID_32 = (ChipID[0]<<16) + (ChipID[1]<<8) + (ChipID[2]);
	
	if(ChipID_32!=Dev_FILE->BlockChipID){
		rt_kprintf("Error: Can't find %s\r\n",Dev_FILE->BlockDevName);
        return RT_ERROR;
	}
	
	/* Make the file system */
	rt_sfud_flash_probe(Dev_FILE->BlockDevName, Dev_FILE->SpiDevName);
	
	if(Dev_FILE->IfFormatting == true){
		dfs_mkfs("elm", Dev_FILE->BlockDevName);
		rt_kprintf("Info: File system formatting completed\r\n");
	}
	
	res = dfs_mount(Dev_FILE->BlockDevName,"/","elm",0,0);
	if(res == -1){
		rt_kprintf("Error: File system mounted failed\r\n");
		return RT_ERROR;
	}
	
    return RT_EOK;
}





/************************ (C) COPYRIGHT 2020 WANGXI **************END OF FILE****/



